import clr # pip install pythonnet
import sys
import os
import time
import threading

# 添加 DLL 路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
clr.AddReference("LibreHardwareMonitorLib")
clr.AddReference("System")

from LibreHardwareMonitor.Hardware import Computer

class HardwareMonitor:
    def __init__(self):
        self.computer = Computer()
        self.computer.IsCpuEnabled = True
        self.computer.IsGpuEnabled = True
        self.computer.IsMotherboardEnabled = True
        self.computer.IsMemoryEnabled = True
        self.computer.IsStorageEnabled = True
        self.computer.IsNetworkEnabled = True
        self.computer.Open()

        self.Cpu_Temp = 0
        self.Cpu_Load = 0
        self.Gpu_Temp = 0
        self.Gpu_Load = 0
        self.Ram_Load = 0

        self.refresh_interval = 5  # 秒
        self._running = False
        self._thread = None
        self.dataIsAvailable = False
    
    def is_dataReady(self):
        return self.dataIsAvailable

    def read_hardware(self, hardware):
        hardware.Update()
        for sensor in hardware.Sensors:
            if sensor.Value is None:
                continue

            name = sensor.Name
            stype = sensor.SensorType
            value = sensor.Value

            # Debug：显示所有可用 sensor
            # print(f"Sensor: {name}, Type: {stype}, Value: {value}")

            if hardware.HardwareType == hardware.HardwareType.Cpu:
                if stype == sensor.SensorType.Temperature and value > 10:
                    self.Cpu_Temp = value
                elif name == "CPU Total" and stype == sensor.SensorType.Load:
                    self.Cpu_Load = value

            elif hardware.HardwareType == hardware.HardwareType.GpuNvidia:
                if stype == sensor.SensorType.Temperature:
                    self.Gpu_Temp = value
                elif stype == sensor.SensorType.Load:
                    self.Gpu_Load = value

            elif hardware.HardwareType == hardware.HardwareType.Memory:
                if stype == sensor.SensorType.Load:
                    self.Ram_Load = value

        for sub in hardware.SubHardware:
            self.read_hardware(sub)

    def read_loop(self):
        while self._running:
            for hw in self.computer.Hardware:
                self.read_hardware(hw)
            # print("\n📊 当前传感器状态：")
            # print(f"  CPU温度: {self.Cpu_Temp:.1f}°C")
            # print(f"  CPU负载: {self.Cpu_Load:.1f}%")
            # print(f"  GPU温度: {self.Gpu_Temp:.1f}°C")
            # print(f"  GPU负载: {self.Gpu_Load:.1f}%")
            # print(f"  内存负载: {self.Ram_Load:.1f}%")
            self.dataIsAvailable = True
            time.sleep(self.refresh_interval)

    def start(self):
        if self._thread and self._thread.is_alive():
            print("监控已在运行中。")
            return
        self._running = True
        self._thread = threading.Thread(target=self.read_loop, daemon=True)
        self._thread.start()
        print("✅ 已启动硬件监控线程")

    def stop(self):
        if not self._running:
            print("监控线程未运行。")
            return
        self._running = False
        if self._thread:
            self._thread.join()
            print("🛑 已停止硬件监控线程")
    def set_refresh_interval(self, interval):
        if interval > 0:
            self.refresh_interval = interval
            print(f"设置刷新间隔为 {interval} 秒")




if __name__ == "__main__":
    monitor = HardwareMonitor()
    monitor.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        monitor.stop()
